package com.uit.smarttool.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.uit.smarttool.dto.CT_GioHang;
import com.uit.smarttool.ultility.CallSoap;
import com.uit.smarttool.ultility.CustomCartView;

public final class Tab1Activity extends Activity {
	ListView lvcart;
	CustomCartView adapter;
	public static ArrayList<CT_GioHang> listCart;
	static AlertDialog alert;
	static String resultDeleteGioHang = "";
	static String resultCheckSL = "";
	static String resultInsertGioHang = "";
	static String resultCheckout = "";
	static String resultCart = "";
	static String resultDelete = "";
	static String resultSoLuong = "";
	ArrayList<CT_GioHang> ll;
	CT_GioHang ct = new CT_GioHang();
	private ArrayList<HashMap<String, String>> list;
	public static int MaSP;
	private int itemId;
	EditText edtDialogQuality;
	TextView tvTotal;
	public static double TongTien;
	Button btnCheckout;
	public static int MaGH;
	public CT_GioHang ct_giohang;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layoutcart);
		lvcart = (ListView) findViewById(R.id.lvCart);
		tvTotal = (TextView) findViewById(R.id.tvTotal);
		btnCheckout = (Button) findViewById(R.id.btnCheckout);
		MaGH = LoginActivity.MaGH;
		listCart = new ArrayList<CT_GioHang>();

		getCart c = new getCart();
		try {
			resultCart = "START";
			c.join();
			c.start();
			while (resultCart == "START") {
				try {
					Thread.sleep(10);
				} catch (Exception ex) {
				}
			}
		} catch (Exception e) {
		}
		TongTien = thanhtoan();
		tvTotal.setText(String.valueOf(TongTien));
		mapDataToList();
		adapter = new CustomCartView(this, list);

		lvcart.setAdapter(adapter);

		lvcart.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				String[] item = readStringListView(adapter.getItem(arg2)
						.toString());

				showDialog(item[5] + "\nGiá: " + item[3]
						+ "\nSố lượng hiện tại: " + item[1]);

				itemId = arg2;
			}

		});

		btnCheckout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialogQA();
			}
		});

	}

	private void mapDataToList() {

		list = new ArrayList<HashMap<String, String>>();


		for (int i = 0; i < listCart.size(); i++) {

			HashMap<String, String> temp = new HashMap<String, String>();
			temp.put("Cot1", listCart.get(i).getTensp());
			temp.put("Cot2", String.valueOf(listCart.get(i).getDongia()));
			temp.put("Cot3", String.valueOf(listCart.get(i).getSoluong()));
			list.add(temp);
		}

	}

	public static double thanhtoan() {
		double thanhtoan = 0;
		int temp = LoginActivity.user_info.getMaloaitk();
		double giamgia = 0.0;
		if (temp == 1) {
			temp = 1;
			giamgia = (double) temp / 100;
		} else if (temp == 2) {
			temp = 3;
			giamgia = (double) temp / 100;
		} else if (temp == 3) {
			temp = 5;
			giamgia = (double) temp / 100;
		}

		if (listCart == null) {
			return thanhtoan = 0;
		} else {
			for (int i = 0; i < listCart.size(); i++) {
				double tmp = (Double.valueOf(listCart.get(i).getSoluong()))
						* (Double.valueOf(listCart.get(i).getDongia()));
				thanhtoan += tmp;
			}
			return thanhtoan - thanhtoan * giamgia;
		}
	}

	public void showDialogQA() {
		final Dialog dialog = new Dialog(Tab1Activity.this);
		dialog.setContentView(R.layout.layoutdialogqa);
		dialog.setTitle("Thông Báo");
		TextView tvDialog = (TextView) dialog.findViewById(R.id.tvThongBao);
		Button btnOk = (Button) dialog.findViewById(R.id.btnok);
		Button btnCancel = (Button) dialog.findViewById(R.id.btncancel);
		tvDialog.setText("Bạn có muốn thanh toán giỏ hàng hay không ?");
		dialog.show();
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				checkSoLuong c4 = new checkSoLuong();
				try {
					resultCheckSL = "START";
					c4.join();
					c4.start();
					while (resultCheckSL == "START") {
						try {
							Thread.sleep(10);
						} catch (Exception ex) {
						}
					}
				} catch (Exception e) {
				}

				if (checkSLTon == 1) {
					checkout c = new checkout();

					try {

						resultCheckout = "START";
						c.join();
						c.start();
						while (resultCheckout == "START") {
							try {
								Thread.sleep(10);
							} catch (Exception ex) {
							}
						}
					} catch (Exception e) {
					}
					if (kqThanhToan == 1) {

						insertGioHang cc = new insertGioHang();
						try {
							resultInsertGioHang = "START";
							cc.join();
							cc.start();
							while (resultInsertGioHang == "START") {
								try {
									Thread.sleep(10);
								} catch (Exception ex) {
								}
							}
						} catch (Exception e) {
						}
						getCart ccc = new getCart();
						try {
							resultCart = "START";
							ccc.join();
							ccc.start();
							while (resultCart == "START") {
								try {
									Thread.sleep(10);
								} catch (Exception ex) {
								}
							}
						} catch (Exception e) {
						}
						Toast.makeText(getApplicationContext(),
								"Thanh toán thành công", 2000).show();
					} else {
						Toast.makeText(getApplicationContext(),
								"Tài khoản không đủ", 2000).show();
					}

				} else {
					Toast.makeText(getApplicationContext(),
							"Sản phẩm " + sanphamthieu + " ko đủ trong kho...",
							2000).show();
				}

				dialog.dismiss();
			}
		});
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
	}

	public void showDialog(String item) {
		final Dialog dialog = new Dialog(Tab1Activity.this);
		dialog.setContentView(R.layout.layoutdialog);
		dialog.setTitle("Thông tin sản phẩm");
		TextView tvDialog = (TextView) dialog.findViewById(R.id.tvDialog);
		Button btnDialogDelete = (Button) dialog
				.findViewById(R.id.btnDialogDelete);
		Button btnDialogAdd = (Button) dialog.findViewById(R.id.btnDialogAdd);
		// Button btnDialogBack = (Button)
		// dialog.findViewById(R.id.btnDialogBack);
		edtDialogQuality = (EditText) dialog
				.findViewById(R.id.edtDialogQuality);
		tvDialog.setText(item);
		dialog.show();
		btnDialogDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				deleteCT_GioHang c4 = new deleteCT_GioHang();
				try {
					resultDelete = "START";
					c4.join();
					c4.start();
					while (resultDelete == "START") {
						try {
							Thread.sleep(10);
						} catch (Exception ex) {
						}
					}
				} catch (Exception e) {
				}
				Toast.makeText(getApplicationContext(), "Xóa thành công", 2000)
						.show();
				dialog.dismiss();
			}
		});

		btnDialogAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (edtDialogQuality.getText().toString().equals("")) {
					dialog.dismiss();
				} else {
					updateSoLuong c = new updateSoLuong();
					try {
						resultSoLuong = "START";
						c.join();
						c.start();
						while (resultSoLuong == "START") {
							try {
								Thread.sleep(10);
							} catch (Exception ex) {
							}
						}
					} catch (Exception e) {
					}

					if (MaGH != 0) {
						getCart cc = new getCart();
						try {
							resultCart = "START";
							cc.join();
							cc.start();
							while (resultCart == "START") {
								try {
									Thread.sleep(10);
								} catch (Exception ex) {
								}
							}
						} catch (Exception e) {
						}
					}
					mapDataToList();
					adapter.notifyDataSetChanged();
					tvTotal.setText(String.valueOf(thanhtoan()));
					Toast.makeText(getApplicationContext(), "Thêm thành công",
							2000).show();
					dialog.dismiss();

				}

			}
		});
	}

	// create new cart after checkout
	private class insertGioHang extends Thread {
		public void run() {
			try {
				CallSoap cs = new CallSoap();
				MaGH = cs.getGioHangIDMax();
				MaGH += 1;
				cs.insertGioHang(String.valueOf(MaGH), getDateNow(), 0,
						String.valueOf(LoginActivity.user_info.getMakh()), 0);
				cs.insertCTGioHang(String.valueOf(MaGH), "18", 0);
				Tab1Activity.resultInsertGioHang = "Finish";
			} catch (Exception ex) {
				Tab1Activity.resultInsertGioHang = ex.toString();
			}
		}
	}

	private int kqThanhToan;

	// checkout
	private class checkout extends Thread {

		public void run() {
			try {
				CallSoap cs = new CallSoap();
				kqThanhToan = 0;
				MaGH = MaGH;
				kqThanhToan = cs.checkoutGioHang(String.valueOf(MaGH),
						String.valueOf(LoginActivity.user_info.getMakh()),
						String.valueOf(LoginActivity.user_info.getSoTien()));

				for (int i = 0; i < listCart.size(); i++) {
					cs.setSLTon(String.valueOf(listCart.get(i).getMasp()),
							listCart.get(i).getSoluong());
				}

				if (TongTien >= 500000 && kqThanhToan == 1) {
					cs.setDiemThuongKH(String.valueOf(LoginActivity.user_info
							.getMakh()));
					Tab1Activity.resultCheckout = "Finish";
				} else if (kqThanhToan == 1) {
					Tab1Activity.resultCheckout = "Finish";
				} else if (kqThanhToan == 0) {
					Toast.makeText(getApplicationContext(),
							"Có sự cố xẩy ra...", 3000).show();
				}

			} catch (Exception ex) {
				Tab1Activity.resultCheckout = ex.toString();
			}
		}
	}

	private int checkSLTon;
	private String sanphamthieu;

	private class checkSoLuong extends Thread {
		@Override
		public void run() {
			try {
				CallSoap cs = new CallSoap();
				checkSLTon = 0;
				for (int i = 0; i < listCart.size(); i++) {
					checkSLTon = cs.checkSLTon(String.valueOf(listCart.get(i)
							.getMasp()), listCart.get(i).getSoluong());
					if (checkSLTon == 0) {
						sanphamthieu = listCart.get(i).getTensp();
						Toast.makeText(
								getApplicationContext(),
								"Sản phẩm " + sanphamthieu
										+ " ko đủ trong kho...", 3000).show();
					}
				}
				Tab1Activity.resultCheckSL = "Finish";
			} catch (Exception ex) {
				Tab1Activity.resultCheckSL = ex.toString();
			}
		}
	}

	// load data to listview
	private class getCart extends Thread {

		public void run() {
			try {
				CallSoap cs = new CallSoap();

				listCart = cs.getCTGioHang(MaGH);
				TongTien = thanhtoan();
				cs.updateTien(String.valueOf(MaGH), String.valueOf(TongTien));
				Tab1Activity.resultCart = "Finish";
			} catch (Exception ex) {
				Tab1Activity.resultCart = ex.toString();
			}
		}
	}

	// thread for inserting data to db
	private class deleteCT_GioHang extends Thread {

		public void run() {
			try {
				CallSoap cs = new CallSoap();
				cs.deleteCTGioHang(String.valueOf(MaGH),
						String.valueOf(listCart.get(itemId).getMasp()));
				Tab1Activity.resultDelete = "Finish";
			} catch (Exception ex) {
				Tab1Activity.resultDelete = ex.toString();
			}

		}
	}

	// thread for inserting data to db
	private class updateSoLuong extends Thread {

		public void run() {
			try {
				CallSoap cs = new CallSoap();
				/*
				 * if (String.valueOf(listCart.get(itemId).getMasp())){
				 * 
				 * }
				 */
				cs.updateSoLuong(String.valueOf(MaGH),
						String.valueOf(listCart.get(itemId).getMasp()),
						Integer.valueOf(edtDialogQuality.getText().toString()));
				Tab1Activity.resultSoLuong = "Finish";
			} catch (Exception ex) {
				Tab1Activity.resultSoLuong = ex.toString();
			}

		}
	}

	// get data from listview
	public String[] readStringListView(String input) {

		String[] tempPart = input.split(",");
		String[] tempQuality = tempPart[0].split("=");
		String[] tempPrice = tempPart[1].split("=");
		String[] tempProduct = tempPart[2].split("=");
		String tmp = tempProduct[1].replace("}", "");

		// 0 1 2 3 4 5
		String[] kq = { tempQuality[0], tempQuality[1], tempPrice[0],
				tempPrice[1], tempProduct[0], tmp };
		return kq;
	}

	// get data from contents of QRCode
	public String[] readString(String input) {
		String[] tempPart = input.split(";");
		String[] tempMa = tempPart[0].split(":");
		String[] tempTen = tempPart[1].split(":");
		String[] tempGia = tempPart[2].split(":");

		// 0 1 2 3 4 5
		String[] kq = { tempMa[0], tempMa[1], tempTen[0], tempTen[1],
				tempGia[0], tempGia[1] };
		return kq;
	}

	public String getDateNow() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm:ss");
		return dateFormat.format(cal.getTime());
	}
}
